package com.ruoyi.business.utils;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

public class ChartImgUtil {
    // 生成美化后的饼图
    public static byte[] createPieChart(String title, String[] names, double[] values) throws IOException {
        DefaultPieDataset dataset = new DefaultPieDataset();
        for (int i = 0; i < names.length; i++) {
            dataset.setValue(names[i], values[i]);
        }
        JFreeChart chart = ChartFactory.createPieChart(title, dataset, false, false, false);
        chart.setBackgroundPaint(Color.WHITE);
        chart.getTitle().setFont(new Font("微软雅黑", Font.BOLD, 18));
        PiePlot plot = (PiePlot) chart.getPlot();
        plot.setBackgroundPaint(Color.WHITE);
        plot.setLabelFont(new Font("微软雅黑", Font.PLAIN, 14));
        plot.setLabelGap(0.02);
        plot.setOutlineVisible(false);
        plot.setShadowPaint(null);
        plot.setLabelBackgroundPaint(Color.WHITE);
        plot.setLabelOutlinePaint(null);
        plot.setLabelShadowPaint(null);
        // 显示百分比标签
        plot.setSimpleLabels(false);
        plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator(
                "{0}: {1} ({2})", new java.text.DecimalFormat("0"), new java.text.DecimalFormat("0.00%")));
        // 设置扇区颜色
        Color[] colors = {new Color(70, 130, 180), new Color(255, 99, 71)};
        int i = 0;
        for (Object key : dataset.getKeys()) {
            plot.setSectionPaint((Comparable<?>) key, colors[i % colors.length]);
            i++;
        }
        BufferedImage image = chart.createBufferedImage(400, 300);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        return baos.toByteArray();
    }

    // 生成美化后的柱状图
    public static byte[] createBarChart(String title, String[] categories, int[] values) throws IOException {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for (int i = 0; i < categories.length; i++) {
            dataset.addValue(values[i], "人数", categories[i]);
        }
        JFreeChart chart = ChartFactory.createBarChart(title, "类别", "人数", dataset, PlotOrientation.VERTICAL, false, true, false);
        chart.setBackgroundPaint(Color.WHITE);
        chart.getTitle().setFont(new Font("微软雅黑", Font.BOLD, 18));
        CategoryPlot plot = chart.getCategoryPlot();
        plot.setBackgroundPaint(Color.WHITE);
        plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
        plot.getDomainAxis().setLabelFont(new Font("微软雅黑", Font.PLAIN, 14));
        plot.getDomainAxis().setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 10));
        plot.getDomainAxis().setMaximumCategoryLabelWidthRatio(1.0f);
        org.jfree.chart.axis.CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setCategoryLabelPositions(org.jfree.chart.axis.CategoryLabelPositions.UP_45);
        plot.getRangeAxis().setLabelFont(new Font("微软雅黑", Font.PLAIN, 14));
        plot.getRangeAxis().setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setBarPainter(new StandardBarPainter());
        renderer.setSeriesPaint(0, new Color(70, 130, 180));
        renderer.setShadowVisible(false);
        renderer.setDrawBarOutline(false);
        renderer.setMaximumBarWidth(0.15);
        // 显示每个柱子的数值
        renderer.setDefaultItemLabelsVisible(true);
        renderer.setDefaultItemLabelGenerator(new org.jfree.chart.labels.StandardCategoryItemLabelGenerator());
        renderer.setDefaultItemLabelFont(new Font("微软雅黑", Font.BOLD, 12));
        renderer.setDefaultItemLabelPaint(Color.BLACK);
        renderer.setDefaultPositiveItemLabelPosition(
            new org.jfree.chart.labels.ItemLabelPosition(
                org.jfree.chart.labels.ItemLabelAnchor.INSIDE12,
                org.jfree.chart.ui.TextAnchor.BOTTOM_CENTER
            )
        );
        renderer.setPositiveItemLabelPositionFallback(
            new org.jfree.chart.labels.ItemLabelPosition(
                org.jfree.chart.labels.ItemLabelAnchor.OUTSIDE12,
                org.jfree.chart.ui.TextAnchor.BOTTOM_CENTER
            )
        );
        // 设置Y轴最大值为最大数值的1.1倍
        int maxValue = 0;
        for (int v : values) {
            if (v > maxValue) maxValue = v;
        }
        double upper = Math.ceil(maxValue * 1.2);
        plot.getRangeAxis().setRange(0, upper);
        BufferedImage image = chart.createBufferedImage(400, 300);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        return baos.toByteArray();
    }

    // 生成年级等级人数折线图
    public static byte[] createGradeLevelLineChart(String title, List<String> gradeNames, List<Integer> excellentList, List<Integer> fineList, List<Integer> passList, List<Integer> failList) throws IOException {
        org.jfree.data.category.DefaultCategoryDataset dataset = new org.jfree.data.category.DefaultCategoryDataset();
        for (int i = 0; i < gradeNames.size(); i++) {
            String grade = gradeNames.get(i);
            dataset.addValue(excellentList.get(i), "优秀人数", grade);
            dataset.addValue(fineList.get(i), "良好人数", grade);
            dataset.addValue(passList.get(i), "及格人数", grade);
            dataset.addValue(failList.get(i), "不及格人数", grade);
        }
        JFreeChart chart = org.jfree.chart.ChartFactory.createLineChart(
            title,
            "年级",
            "人数",
            dataset,
            org.jfree.chart.plot.PlotOrientation.VERTICAL,
            true, true, false
        );
        chart.setBackgroundPaint(Color.WHITE);
        chart.getTitle().setFont(new Font("微软雅黑", Font.BOLD, 18));
        org.jfree.chart.plot.CategoryPlot plot = chart.getCategoryPlot();
        plot.setBackgroundPaint(Color.WHITE);
        plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
        plot.getDomainAxis().setLabelFont(new Font("微软雅黑", Font.PLAIN, 14));
        plot.getDomainAxis().setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        plot.getRangeAxis().setLabelFont(new Font("微软雅黑", Font.PLAIN, 14));
        plot.getRangeAxis().setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        // 设置图例字体，防止中文乱码和小方框
        if (chart.getLegend() != null) {
            chart.getLegend().setItemFont(new Font("微软雅黑", Font.PLAIN, 14));
        }
        // 设置线条颜色
        org.jfree.chart.renderer.category.LineAndShapeRenderer renderer = new org.jfree.chart.renderer.category.LineAndShapeRenderer();
        renderer.setSeriesPaint(0, new Color(31, 119, 180)); // 优秀
        renderer.setSeriesPaint(1, new Color(255, 127, 14)); // 良好
        renderer.setSeriesPaint(2, new Color(44, 160, 44)); // 及格
        renderer.setSeriesPaint(3, new Color(214, 39, 40)); // 不及格
        renderer.setDefaultShapesVisible(true);
        renderer.setDefaultItemLabelsVisible(true);
        renderer.setDefaultItemLabelFont(new Font("微软雅黑", Font.BOLD, 12));
        plot.setRenderer(renderer);
        // 设置Y轴最大值为最大人数的1.1倍
        int max = 0;
        for (int v : excellentList) max = Math.max(max, v);
        for (int v : fineList) max = Math.max(max, v);
        for (int v : passList) max = Math.max(max, v);
        for (int v : failList) max = Math.max(max, v);
        double upper = Math.ceil(max * 1.1);
        plot.getRangeAxis().setRange(0, upper);
        BufferedImage image = chart.createBufferedImage(400, 200);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        return baos.toByteArray();
    }
} 